<template>
  <x-form
    ref="formRef"
    v-model:model="formData"
    :rules="rules"
    :label-width="labelWidth"
    :label-placement="labelPlacement"
    :size="size"
  >
    <n-form-item :show-require-mark="required" :disabled="disabled" label="链接" path="linkType">
      <component
        :is="componentTag"
        v-model:value="formData.linkType"
        :options="getLandingOptions()"
        :disabled="isDisabled"
        placeholder="请选择链接"
        check-strategy="child"
        clearable
        @update:value="handleChangeLandingType"
      />
    </n-form-item>
    <n-form-item v-if="isLinkContent" :show-require-mark="required" label="落地" path="linkContent">
      <template v-if="isLinkContentInput">
        <n-space align="center">
          <n-input
            v-model:value="formData.linkContent"
            :maxlength="255"
            :placeholder="linkContentPlaceholder"
            clearable
            @blur="handleChangeLinkContent"
          />
          <n-tooltip placement="left">
            <template #trigger>
              <x-icon name="icon-063" />
            </template>
            {{ linkContentPlaceholder }}
          </n-tooltip>
        </n-space>
      </template>
      <template v-else>
        <x-landing-live
          v-if="isLiveLinkContent"
          v-model:visible="landingLiveVisible"
          v-model:model="formData"
          :type="formData.linkType"
          :options="getLandingOptions(true)"
          :is-group="isGroup"
        >
          <x-button @click="landingLiveVisible = true">配置信息</x-button>
        </x-landing-live>
        <template v-else>
          <n-space v-if="formData.linkContent" align="center">
            <n-tag :disabled="disabled" type="info" closable @close="handleLandingRemove">
              <span v-if="isMultiple">已经关联{{ formData.linkContent.length }}条数据</span>
              <n-ellipsis v-else style="max-width: 139px">
                {{ linkInfoName }}
              </n-ellipsis>
            </n-tag>
            <x-button type="primary" tertiary @click="drawerVisible = true">
              {{ disabled ? '查看' : '编辑' }}
            </x-button>
          </n-space>
          <x-button v-else @click="drawerVisible = true">请选择落地值</x-button>
        </template>
      </template>
    </n-form-item>
  </x-form>

  <x-landing-select
    v-if="drawerVisible"
    v-model:visible="drawerVisible"
    v-model:value="formData.linkContent"
    :tabs="landingTabs"
    :filters="filters"
    :default-value="landingDefaultValue"
    :multiple="isMultiple"
    :multiple-limit="multipleLimit"
    :readonly="disabled"
    :default-form-data="landingSelectDefaultFormData"
    :title="landingSelectTitle"
    :title-desc="landingSelectTitleDesc"
    :required-params="requiredParams"
    :app-id="query.appId"
    :companyName="query.companyName"
    @update:value="handleLandingChange"
  />
</template>

<script lang="ts">
  import { computed, defineComponent, h, nextTick, reactive, ref, toRefs, watch } from 'vue'
  import { NCascader, NEllipsis, NFormItem, NInput, NSelect, NSpace, NTag, NTooltip, NText, useMessage } from 'naive-ui'
  import { XForm, XButton, XIcon, XLandingSelect } from '@/components'
  import { XLandingLive } from '../x-landing-live'
  import { useStore } from '@/store'
  import { isBms } from '@/utils/is'
  import {useRoute} from "vue-router";

  export default defineComponent({
    name: 'XLandingLink',
    components: {
      NSpace,
      NFormItem,
      NSelect,
      NCascader,
      NInput,
      NTooltip,
      NTag,
      NEllipsis,
      NText,
      XForm,
      XButton,
      XIcon,
      XLandingSelect,
      XLandingLive
    },
    props: {
      // 数据结构
      model: {
        type: Object,
        default: () => {}
      },
      // 落地类型
      type: {
        type: Number,
        default: null
      },
      // 落地内容
      content: {
        type: [String, Number],
        default: null
      },
      // 是否必填
      required: {
        type: Boolean,
        default: false
      },
      // 是否禁用
      disabled: {
        type: Boolean,
        default: false
      },
      // 是否为聚合页落地选择
      isGroup: {
        type: Boolean,
        default: false
      },
      // 是否为备用链接配置
      isSpare: {
        type: Boolean,
        default: false
      },
      // 是否支持优惠券选择
      isCoupon: {
        type: Boolean,
        default: false
      },
      labelWidth: {
        type: [Number, String],
        default: 'auto'
      },
      labelPlacement: {
        type: String,
        default: 'left'
      },
      size: {
        type: String,
        default: 'small'
      },
      // 需要过滤不可被选择的值
      filters: {
        type: Array,
        default: () => []
      },
      // 自定义可选项
      options: {
        type: Array,
        default: () => []
      }
    },
    emits: ['update:model', 'change'],
    setup($props, { emit: $emit }) {
      const $route = useRoute()
      const { query } = $route
      const formRef: any = ref(null)
      const $store = useStore()
      const $message = useMessage()
      const $state: any = reactive({
        query,
        ...toRefs($props),
        isBms,
        loading: false,
        drawerVisible: false,
        landingLiveVisible: false,
        formData: {
          ...$props.model
        },
        linkInfo: null,
        rules: {
          linkType: {
            required: $props.required,
            type: 'number',
            message: '请选择链接',
            trigger: 'change'
          },
          linkContent: {
            required: $props.required,
            type: 'any',
            message: '请配置内容',
            trigger: ['change', 'blur']
          }
        },
        // 是否需要配置详情的落地枚举值
        isLinkContent: computed(() => [1, 2, 14, 15, 16, 18, 19, 20, 21, 22, 23].includes($state.formData.linkType)),
        // 视频号相关落地枚举值
        isLiveLinkContent: computed(() => [18, 19, 20, 21, 22].includes($state.formData.linkType)),
        // 需要输入框的落地枚举值
        isLinkContentInput: computed(() => [14, 15].includes($state.formData.linkType)),
        // 输入框提示文案
        linkContentPlaceholder: computed(() => {
          switch ($state.formData?.linkType) {
            case 14:
              return '请输入小程序绝对路径，以/开头'
            case 15:
              return '请输入公众号绝对路径，以https://mp.weixin.qq.com/开头'
            default:
              return '请输入落地内容'
          }
        }),
        // 落地页默认选中tab值
        landingDefaultValue: computed(() => {
          switch ($state.formData.linkType) {
            case 1:
              if ($state.formData.linkContent) {
                if ($state.linkInfo?.type === 3) {
                  return 'group'
                } else {
                  return 'pages'
                }
              } else {
                return null
              }
            default:
              return null
          }
        }),
        // 联动选择禁用逻辑
        isDisabled: computed(() => {
          return $state.isBms
            ? !!$state.formData.linkContent
            : [1, 2, 16, 23].includes($state.formData.linkType)
            ? !!$state.formData.linkContent
            : false
        }),
        // 是否支持多选
        isMultiple: computed(() => {
          return [23].includes($state.formData.linkType)
        }),
        // 可支持多选几个
        multipleLimit: computed(() => {
          return [23].includes($state.formData.linkType) ? 10 : 0
        }),
        // 落地组件的默认
        landingSelectDefaultFormData: computed(() => {
          if ([23].includes($state.formData.linkType)) {
            const params = {
              couponScene: $state.isBms ? 1 : -1
            }
            // 编辑的时候，回填相关数据
            if (!$state.isBms && $state.formData.belongStoreId) {
              params.keyword = $state.formData.belongStoreId
              params.storeId = $state.formData.belongStoreId
            }
            return params
          } else {
            return {}
          }
        }),
        // 落地组件标题
        landingSelectTitle: computed(() => {
          switch ($state.formData.linkType) {
            case 23:
              return '优惠券'
            default:
              return ''
          }
        }),
        // 落地组件标题对应的描述
        landingSelectTitleDesc: computed(() => {
          switch ($state.formData.linkType) {
            case 23:
              return '有效的优惠券'
            default:
              return ''
          }
        }),
        // 落地组件是否有必填参数
        requiredParams: computed(() => {
          switch ($state.formData.linkType) {
            case 23:
              return $state.isBms ? null : ['storeId', 'storeName']
            default:
              return null
          }
        }),
        // 使用下拉选择还是多级联动
        componentTag: computed(() => {
          if ($state.isBms) {
            return h(NSelect)
          } else {
            return h(NCascader)
          }
        }),
        // 选择的落地详情
        linkInfoName: computed(() => {
          const info = $state.linkInfo
          const linkInfoName = []
          if (info) {
            switch (info.linkType) {
              case 2:
                linkInfoName.push('商品')
                break
              case 16:
                linkInfoName.push('推广页')
                break
              case 23:
                linkInfoName.push('优惠券')
                break
              case 1:
                // 1,2微页面；3-聚合页
                linkInfoName.push(info.type === 3 ? '聚合页' : '微页面')
                break
              default:
                break
            }
            linkInfoName.push(info.productName)
          }
          return linkInfoName.join(' | ')
        }),
        // 可选择的落地项
        landingTabs: computed(() => {
          if ($state.isBms && $state.isGroup) {
            // 商家聚合页需要支持两种选择
            switch ($state.formData.linkType) {
              case 1:
                return ['group', 'pages']
              case 2:
                return ['product']
              case 16:
                return ['advertising']
              case 23:
                return ['coupon']
              default:
                return ['group', 'pages', 'product', 'advertising']
            }
          } else {
            // 业务后台和商家普通微页面，仅需要一种即可
            switch ($state.formData.linkType) {
              case 1:
                return ['pages']
              case 23:
                return ['coupon']
              default:
                return ['product']
            }
          }
        })
      })

      // 删除选中的落地数据
      const handleLandingRemove = () => {
        $state.formData.linkContent = null
        $state.linkInfo = null

        // $state.formData.alternateLinkType = null
        // $state.formData.alternateLinkContent = null
        // $state.formData.alternateProductInfo = null
      }

      // 落地可选择的项
      const getLandingOptions = (isSpare?: boolean) => {
        {
          let LANDING_OPTIONS = $state.isBms
            ? [
                {
                  value: 1,
                  label: $state.isGroup ? '聚合页/微页面' : '微页面'
                },
                {
                  value: 2,
                  label: '商品'
                },
                {
                  value: 16,
                  label: '商品推广页'
                }
              ]
            : [
                {
                  value: 9001,
                  label: '系统链接',
                  children: [
                    {
                      value: 3,
                      label: '全部商品'
                    },
                    {
                      value: 4,
                      label: '分类'
                    },
                    {
                      value: 5,
                      label: '排行榜'
                    },
                    // {
                    //   value: 6,
                    //   label: '源头工厂'
                    // },
                    // {
                    //   value: 8,
                    //   label: '活动'
                    // },
                    // {
                    //   value: 9,
                    //   label: '消息'
                    // },
                    {
                      value: 10,
                      label: '我的'
                    }
                  ]
                },
                {
                  value: 1,
                  label: '微页面',
                  disabled: $route.name === 'MarketingPopupDetail'
                },
                {
                  value: 2,
                  label: '商品'
                },
                {
                  value: 9002,
                  label: '视频号路径',
                  children: [
                    {
                      value: 18,
                      label: '视频号主页'
                    },
                    {
                      value: 19,
                      label: '视频号视频'
                    },
                    {
                      value: 20,
                      label: '视频号活动页'
                    }
                  ]
                },
                {
                  value: 9003,
                  label: '自定义路径',
                  children: [
                    {
                      value: 14,
                      label: '小程序路径'
                    },
                    {
                      value: 15,
                      label: '公众号路径'
                    }
                  ]
                }
              ]

          // 优先使用自定义的可选项
          if ($state.options?.length) {
            LANDING_OPTIONS = $state.options
          }
          if ($state.isBms && !$state.isGroup) {
            // 商家端普通微页面，过滤掉16类型
            LANDING_OPTIONS = LANDING_OPTIONS.filter((item: { value: number }) => item.value !== 16)
          }
          // 过滤掉视频号
          if ($props.isSpare || isSpare) {
            LANDING_OPTIONS = LANDING_OPTIONS.filter((item: { value: number }) => item.value !== 9002)
          }
          // 支持优惠券
          if ($state.isCoupon) {
            LANDING_OPTIONS.push({
              value: 23,
              label: '优惠券'
            })
          }
          return LANDING_OPTIONS
        }
      }

      // 切换落地类型
      const handleChangeLandingType = () => {
        handleLandingRemove()
        // 微页面、商品
        if ([1, 2, 16, 23].includes($state.formData.linkType)) {
          nextTick(() => {
            $state.drawerVisible = true
          })
        }
        // 视频号相关类型
        if ([18, 19, 20, 21, 22].includes($state.formData.linkType)) {
          nextTick(() => {
            Object.assign($state.formData, {
              alternateLinkType: null,
              alternateLinkContent: null,
              alternateProductInfo: null
            })
            $state.landingLiveVisible = true
          })
        }
        $emit('change', $state.linkInfo)
      }

      // 落地链接切换处理
      const handleChangeLinkContent = () => {
        const { linkContent, linkType } = $state.formData
        switch (linkType) {
          case 14:
            if (!linkContent) {
              return $message.warning('请输入正确的小程序路径')
            } else {
              let value = linkContent.replace(/\.html/gi, '')
              if (!/^\//.test(value)) {
                value = `/${value}`
              }
              $state.formData.linkContent = value
            }
            break
          case 15:
            if (!/^https:\/\/mp.weixin.qq.com/gi.test(linkContent)) {
              $state.formData.linkContent = null
              return $message.warning('请输入正确的公众号链接地址')
            }
            break
        }
      }

      // 选择落地数据
      const handleLandingChange = (id: string | number, item: any, currentTab: string) => {
        let linkInfo
        // console.log(id, $state.formData.linkType)
        switch (currentTab) {
          case 'group':
          case 'pages':
            linkInfo = {
              linkType: 1,
              type: item?.type,
              linkContent: id,
              productName: item?.title
            }
            break
          case 'product':
            linkInfo = {
              linkType: 2,
              linkContent: id,
              productName: item?.productTitle
            }
            break
          case 'advertising':
            linkInfo = {
              linkType: 16,
              linkContent: id,
              productName: item?.pageName
            }
            break
          case 'coupon':
            linkInfo = {
              linkType: 23,
              linkContent: id,
              productName: item?.couponName
            }
            break
          default:
            linkInfo = {
              linkType: $state.formData.linkType,
              linkContent: id,
              productName: item?.title
            }
            break
        }
        $state.linkInfo = linkInfo
        $emit('change', linkInfo)
      }

      // 获取落地对应的商品或页面详情
      const getContentListInfo = (linkType?: number, linkContent?: string | number) => {
        const type = linkType || $state.formData?.linkType
        const content = linkContent || $state.formData?.linkContent
        return new Promise((resolve) => {
          if (![1, 2, 16, 23].includes(type) || !content) {
            return resolve(null)
          }
          let api = ''
          let payload
          let value: string | number = content
          switch (type) {
            case 1:
              // 页面
              api = 'decoration/getPagesDetail'
              payload = {
                pageId: value
              }
              break
            case 2:
              // 商品
              api = 'marketing/getProductDetail'
              payload = {
                type: 1,
                id: value
              }
              break
            case 16:
              // 商品投放页
              api = 'marketing/getAdPageDetail'
              payload = {
                type: 1,
                id: value
              }
              break
            case 23:
              // 优惠券
              api = 'marketing/couponDetail'
              payload = {
                couponId: value
              }
              break
          }
          $store.dispatch(api, payload).then((res) => {
            const detail: any = res.data
            if (detail) {
              let linkInfo
              if (type === 1 && detail.pageType) {
                // 微页面，非草稿页面
                linkInfo = {
                  linkType: 1,
                  id: detail.id,
                  // 1,2微页面；3-聚合页
                  type: detail.type,
                  linkContent: detail.id,
                  productName: detail.title
                }
              } else if (type === 2 && detail.displayStatus === 1 && detail.productStatus === 1) {
                // 商品，上架&&显示
                linkInfo = {
                  id: detail.id,
                  linkType: 2,
                  linkContent: detail.id,
                  productName: detail.productTitle,
                  productPic: detail.productMainPic,
                  price: detail.groupPrice,
                  sales: detail.salesNum
                }
              } else if (type === 16) {
                linkInfo = {
                  id: detail.id,
                  linkType: 16,
                  linkContent: detail.id,
                  productName: detail.pageName
                }
              } else if (type === 23) {
                linkInfo = {
                  id: detail.id,
                  linkType: 23,
                  linkContent: detail.id,
                  productName: detail.couponName
                }
              }
              resolve(linkInfo)
            }
          })
        })
      }

      // 校验必填
      const validate = () => {
        return new Promise((resolve, reject) => {
          formRef.value.validate((errors: []) => {
            if (!errors) {
              resolve(true)
            } else {
              reject(errors)
            }
          })
        })
      }

      // 初始时获取一次配置的落地数据
      const initializeContentListInfo = () => {
        if ($state.loading || $state.isMultiple) return false
        $state.loading = true
        const { linkType, linkContent, alternateLinkType, alternateLinkContent } = $state.formData
        // 获取主配置项落地详情
        if (!$state.linkInfo) {
          getContentListInfo(linkType, linkContent).then((res: any) => {
            $state.linkInfo = res
            $state.loading = false
          })
        }
        // 获取备用配置项落地详情
        if (alternateLinkType && alternateLinkContent && !$state.formData.alternateProductInfo) {
          getContentListInfo(alternateLinkType, alternateLinkContent).then((res: any) => {
            Object.assign($state.formData, {
              alternateProductInfo: res
            })
            $state.loading = false
          })
        }
      }
      initializeContentListInfo()

      // 更新数据
      watch(
        () => $props.model,
        (value) => {
          Object.assign($state.formData, value || {})
          initializeContentListInfo()
        },
        {
          deep: true
        }
      )

      // 更新数据
      watch(
        () => [
          $state.formData.linkType,
          $state.formData.linkContent,
          $state.formData.alternateLinkType,
          $state.formData.alternateLinkContent
        ],
        () => {
          $emit('update:model', $state.formData)
        },
        {
          deep: true
        }
      )

      return {
        ...toRefs($state),
        formRef,
        validate,
        handleLandingRemove,
        handleChangeLandingType,
        handleChangeLinkContent,
        handleLandingChange,
        getLandingOptions
      }
    }
  })
</script>

<style></style>
